//
//  UserDefaultsManager.swift
//  imember_printer
//
//  Created by feibi on 2022/1/17.
//

import UIKit
import PrinterSDK

class UserDefaultsManager: NSObject {
    static let printerKey = "ImemberPrinter"
    
    /// 獲取本地緩存的設備
    static var printers: [PTPrinter] {
        if let data = UserDefaults.standard.data(forKey: printerKey),
            let models = NSKeyedUnarchiver.unarchiveObject(with: data) as? [PTPrinter] {
            return models
        }
        return []
    }
    
    /// 緩存設備
    static func setPrinter(_ printer: PTPrinter) {
        var printers = printers.filter() { $0.ip != printer.ip  }
        printers.insert(printer, at: 0)
        let data = NSKeyedArchiver.archivedData(withRootObject: printers)
        UserDefaults.standard.set(data, forKey: printerKey)
        UserDefaults.standard.synchronize()
    }
    
    /// 刪除本地緩存的設備
    static func removePrinter() {
        UserDefaults.standard.removeObject(forKey: printerKey)
        UserDefaults.standard.synchronize()
    }
}
